package com.elitel.frame.business.service.impl;

import com.elitel.base.entity.sqlparse.InputParam;
import com.elitel.base.entity.sqlparse.SqlData;
import com.elitel.common.MyBatisSqlUtils;
import com.elitel.common.SqlHelper;
import com.elitel.common.core.exception.GlobalException;
import com.elitel.common.core.log.enums.ResultCodeEnum;
import com.elitel.common.exception.BaseException;
import com.elitel.common.mongodb.MongoDBUtil;
import com.elitel.common.mongodb.QueryInfo;
import com.elitel.common.utils.ObjectUtil;
import com.elitel.common.utils.XCommonUtils;
import com.elitel.frame.base.component.RedisCacheComponent;
import com.elitel.frame.base.component.RedisCatchCensus;
import com.elitel.frame.base.service.strategy.sql.OgnlParseSQLStrategy;
import com.elitel.frame.business.dao.ext.CensusSearchMapper;
import com.elitel.frame.business.dao.ext.ExecuteSqlMapper;
import com.elitel.frame.business.service.CensusSearchService;
import com.elitel.frame.main.dao.*;
import com.elitel.frame.main.dao.ext.ExtCfgTableMapper;
import com.elitel.frame.main.dao.ext.ExtSysExceptionMapper;
import com.elitel.frame.main.entity.*;
import com.elitel.frame.main.entity.enums.ParseSQLEnum;
import com.elitel.frame.main.entity.ext.MyBatisSql;
import com.elitel.frame.main.entity.ext.StaconfigJsonVo;
import com.elitel.frame.main.entity.vo.JsonResult;
import com.elitel.frame.main.entity.vo.PageResponseVo;
import com.google.gson.Gson;
import com.mongodb.BasicDBObject;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import net.sf.json.JSONObject;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.*;
import java.util.Date;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class CensusSearchServiceImpl implements CensusSearchService {

    @Resource
    private CfgExtstaMapper cfgExtstaMapper;

    @Resource
    private BaseStaconfigMapper baseStaconfigMapper;

    @Resource
    private CensusSearchMapper censusSearchMapper;

    @Resource
    private ExecuteSqlMapper executeSqlMapper;

    @Resource
    private ExtCfgTableMapper extCfgTableMapper;

    @Resource
    private BaseSqlconfigMapper baseSqlconfigMapper;

    @Resource
    private CfgFieldMapper cfgFieldMapper;

    @Resource
    private BaseStaaddonsMapper baseStaaddonsMapper;

    @Resource
    private RedisCacheComponent redisCacheComponent;
//  @Resource private RedisCacheService redisCacheService;

    @Resource
    private RedisCatchCensus redisCatchCensus;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Resource
    private OgnlParseSQLStrategy ognlParseSQLStrategy;

    //	@Autowired
    //    private JmsTemplate jmsTemplate;
    //
    //	@Resource(name = "serverQueueDestination")
    //    private Destination destination;
    //	@Autowired
    //    private AmqpTemplate amqpTemplate;
    //
    //	@Autowired
    //	private RabbitTemplate rabbitTemplate;

    @Resource
    private ExtSysExceptionMapper extSysExceptionMapper;

    private int rdi = 0;

    // 子字符串modelStr在字符串str中第count次出现时的下标
    public static int getFromIndex(String str, String modelStr, Integer count) {
        System.out.println(str.length());
        // 对子字符串进行匹配
        Matcher slashMatcher = Pattern.compile(modelStr).matcher(str);
        int index = 0;
        // matcher.find();尝试查找与该模式匹配的输入序列的下一个子序列
        while (slashMatcher.find()) {
            index++;
            // 当modelStr字符第count次出现的位置
            if (index == count) {
                break;
            }
        }
        // matcher.start();返回以前匹配的初始索引。
        return slashMatcher.start();
    }

    @Override
    public Map<String, Object> getCensusSearch(CfgDb prop, String serviceID, String conQuery) {
        CfgExtsta cfgExtsta = cfgExtstaMapper.selectByPrimaryKey(serviceID);
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<String, Object>();
        map = gson.fromJson(conQuery, map.getClass());
        List<BaseStaconfig> list = baseStaconfigMapper.selectSearchStaConfigList(cfgExtsta.getGuid());
        String x = "";
        String y = "";
        String converge = ",${converge} AS converge ";
        String tableWhe = "";
        Map<String, Object> maping = new HashMap<String, Object>();
        // String sqlString = "SELECT #{"+x+"} AS xField ,#{"+y+"} AS
        // yField"+converge+" FROM "+tableWhe;
        for (BaseStaconfig baseStaconfig : list) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                if (entry.getKey().equals(baseStaconfig.getDtConfigId())) {
                    if (baseStaconfig.getSwheresql() == null || "".equals(baseStaconfig.getSwheresql())) {
                        Map<String, Object> maped = new HashMap<String, Object>();
                        maped = gson.fromJson((String) entry.getValue(), map.getClass());
                        int i = 0;
                        for (Map.Entry<String, Object> entry2 : maped.entrySet()) {
                            String valuees = (String) entry2.getValue();
                            int start = getFromIndex(valuees, " ", 1);
                            String a = valuees.substring(0, start);
                            String b = valuees.substring(start + 1);
                            if (i == 0) {
                                tableWhe += entry2.getKey() + " " + a + " " + b;
                            } else {
                                tableWhe = "and " + entry2.getKey() + " " + a + " " + b;
                            }
                            i++;
                            tableWhe = "WHERE " + tableWhe;
                        }

                    } else {
                        Map<String, Object> maped = new HashMap<String, Object>();
                        maped = gson.fromJson((String) entry.getValue(), map.getClass());
                        for (Map.Entry<String, Object> entry2 : maped.entrySet()) {
                            String valuees = (String) entry2.getValue();
                            int start = getFromIndex(valuees, " ", 1);
                            String a = valuees.substring(0, start);
                            String b = valuees.substring(start + 1);
                            tableWhe =
                                    baseStaconfig.getSwheresql() + "and " + entry2.getKey() + " " + a + " " + b;
                        }
                    }
                }
            }
            if (baseStaconfig.getIsgroup() == 1) {
                tableWhe =
                        baseStaconfig.getDtConfigId()
                                + " "
                                + tableWhe
                                + " "
                                + "GROUP BY "
                                + baseStaconfig.getYfield();
            } else {
                tableWhe = baseStaconfig.getDtConfigId() + " " + tableWhe + " ";
            }
            String sqlString =
                    "SELECT #{"
                            + baseStaconfig.getXfield()
                            + "} AS xField ,#{"
                            + baseStaconfig.getYfield()
                            + "} AS yField ,${"
                            + baseStaconfig.getStatype()
                            + "} AS converge "
                            + converge
                            + " FROM "
                            + tableWhe;

            List<StaconfigJsonVo> staconfigJsonVo = censusSearchMapper.getCensusSearch(sqlString);

            maping.put(baseStaconfig.getDtConfigId(), staconfigJsonVo);
        }
        return maping;
    }

    @Override
    public Map<String, Object> getCensusTableing(CfgDb prop, String serviceID, String conQuery) {
        CfgExtsta cfgExtsta = cfgExtstaMapper.selectByPrimaryKey(serviceID);
        Gson gson = new Gson();
        Map<String, Object> maped = new HashMap<String, Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        map = gson.fromJson(conQuery, map.getClass());
        List<BaseStaconfig> list = baseStaconfigMapper.selectSearchStaConfigList(cfgExtsta.getGuid());
        String x = "";
        String y = "";
        String xString = "";
        String tableWhe = "";
        int i = 0;
        int j = 0;
        for (BaseStaconfig baseStaconfig : list) {
            i = 0;
            Map<String, Object> maping = selectWher(baseStaconfig.getGuid());
            for (Map.Entry<String, Object> entry : maping.entrySet()) {
                if (map.get(entry.getKey()) != null && !"".equals(map.get(entry.getKey()))) {
                    if (i == 0) {
                        tableWhe +=
                                " " + entry.getKey() + " " + entry.getValue() + " " + map.get(entry.getKey()) + " ";
                    } else {
                        tableWhe +=
                                "AND"
                                        + " "
                                        + entry.getKey()
                                        + " "
                                        + entry.getValue()
                                        + " "
                                        + map.get(entry.getKey())
                                        + " ";
                    }
                    j = 1;
                }
                i++;
            }
            // tableWhe="";
            String xfrt = "SELECT COUNT(1) AS cou FROM " + baseStaconfig.getDtConfigId() + " ";
            int count = executeSqlMapper.executequerySqlCount(xfrt);
            if (j == 1) {
                if (tableWhe == null || "".equals(tableWhe)) {
                    tableWhe = "WHERE" + "" + tableWhe + " rownum <100 ";
                } else {
                    tableWhe = "WHERE" + "" + tableWhe + " AND rownum <100 ";
                }
            } else {
                tableWhe = "WHERE rownum <100 ";
            }
            tableWhe =
                    baseStaconfig.getDtConfigId()
                            + " "
                            + tableWhe
                            + " "
                            + "GROUP BY "
                            + baseStaconfig.getYfield()
                            + ","
                            + baseStaconfig.getXfield();
            xString = baseStaconfig.getStatype();
            String converge = xString + " AS yField ";
            String sqlString = "";
            if (baseStaconfig.getStatype() != null && !"".equals(baseStaconfig.getStatype())) {
                sqlString =
                        "SELECT " + baseStaconfig.getXfield() + " AS xField ," + converge + "FROM " + tableWhe;
            } else {
                sqlString = "SELECT " + baseStaconfig.getXfield() + " AS xField  FROM " + tableWhe;
            }

            List<Map<String, Object>> list2 = executeSqlMapper.executequerySql(sqlString);
            // List<StaconfigJsonVo> staconfigJsonVo =
            // censusSearchMapper.getCensusSearch(sqlString);

            maped.put(baseStaconfig.getDtConfigId(), list2);

            tableWhe = "";
        }
        return maped;
    }

    public Map<String, Object> selectWher(String guid) {
        Map<String, Object> map = new HashMap<String, Object>();
        String message = baseStaconfigMapper.selectWher(guid);
        String aa = message.substring(5);
        String[] bb = aa.split("and");
        // GUID > ce15
        Map<String, Object> maping = new HashMap<String, Object>();
        List<String> ccList = Arrays.asList(bb);
        for (String ss : ccList) {
            int a = getFromIndex(ss, " ", 1);
            int b = getFromIndex(ss, " ", 2);
            int c = getFromIndex(ss, " ", 3);
            String ad = ss.substring(a + 1, b);
            String bd = ss.substring(b + 1, c);
            String cd = ss.substring(c + 1, ss.length() - 1);
            maping.put(ad, bd);
        }
        return maping;
    }

    @Override
    public Map<String, Object> getCensusTableed(CfgDb prop, String serviceID, String conQuery) {
        CfgExtsta cfgExtsta = cfgExtstaMapper.selectByPrimaryKey(serviceID);
        Gson gson = new Gson();
        Map<String, Object> maped = new HashMap<String, Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        map = gson.fromJson(conQuery, map.getClass());
        List<BaseStaconfig> list = baseStaconfigMapper.selectSearchStaConfigList(cfgExtsta.getGuid());
        String sqlString = "";
        String xString = "";
        String tableWhe = "";
        for (BaseStaconfig baseStaconfig : list) {
            if (map == null) {
                String xxString = extCfgTableMapper.getBiaoName(baseStaconfig.getDtConfigId());
                tableWhe =
                        extCfgTableMapper.getBiaoName(baseStaconfig.getDtConfigId())
                                + " "
                                + " "
                                + "GROUP BY "
                                + baseStaconfig.getXfield();
            } else {
                String xxString = extCfgTableMapper.getBiaoName(baseStaconfig.getDtConfigId());
                tableWhe =
                        extCfgTableMapper.getBiaoName(baseStaconfig.getDtConfigId())
                                + " "
                                + "where 1=1 "
                                + baseStaconfig.getSwheresql()
                                + " "
                                + "GROUP BY "
                                + baseStaconfig.getXfield()
                                + ","
                                + baseStaconfig.getXfield();
            }
            xString = baseStaconfig.getStatype();
            String converge = xString + " AS yField ";
            if (baseStaconfig.getStatype() != null && !"".equals(baseStaconfig.getStatype())) {
                sqlString =
                        "SELECT " + baseStaconfig.getXfield() + " AS xField ," + converge + "FROM " + tableWhe;
            } else {
                sqlString = "SELECT " + baseStaconfig.getXfield() + " AS xField FROM " + tableWhe;
            }
            if (map != null) {
                sqlString = processSqlByFreemarker(sqlString, map);
            }
            List<Map<String, Object>> list2 = executeSqlMapper.executequerySql(sqlString);
            maped.put(baseStaconfig.getGuid(), list2);
        }
        return maped;
    }

    /**
     * <pre>
     * processSqlByFreemarker(freemarker处理sql)
     * &#64;author：FanWenquan
     * &#64;date：2017年8月31日 上午10:34:17
     * &#64;param sql
     * &#64;param root
     * &#64;return
     * </pre>
     */
    private String processSqlByFreemarker(String sql, Map root) {
        String str = "";
        Configuration cfg = new Configuration();
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("myTemplate", sql);
        cfg.setTemplateLoader(stringLoader);
        try {
            Template template = cfg.getTemplate("myTemplate", "utf-8");
            StringWriter writer = new StringWriter();
            template.process(root, writer);
            str = writer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return str;
    }

    @Override
    public Map<String, String> getCensusTableColumn(CfgDb cfgDb, String serviceString) {
        List<String> list = baseStaconfigMapper.selectColumnMap(serviceString);
        Map<String, String> columnMap = new HashMap<String, String>();
        for (String column : list) {
            if (column != null && !"".equals(column)) {
                JSONObject jsonObject = JSONObject.fromObject(column);
                Map<String, String> map = jsonObject;
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    columnMap.put(entry.getKey(), entry.getValue());
                }
            }
        }
        return columnMap;
    }

    @Override
    public List<String> getBaseSqlColumnList(CfgDb cfgDb, String sqlString) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<String> columnList = new ArrayList<String>();
        String sql = "";
        if ("ORACLE".equals(cfgDb.getDbVersion())) {
            sql =
                    "SELECT * FROM ( SELECT A.*, ROWNUM RN FROM ("
                            + sqlString
                            + ") A WHERE ROWNUM <= 1) WHERE RN >= 0";
            list = executeSqlMapper.executequerySql(sql);
        }
        if ("MYSQL".equals(cfgDb.getDbVersion())) {
            sql = sqlString + "limit 0,1";
            list = executeSqlMapper.executequerySql(sql);
        }
        int a = 0;
        for (Map<String, Object> map : list) {
            if (a == 0) {
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    columnList.add(entry.getKey());
                }
            }
            a++;
        }
        return columnList;
    }

    @Override
    public JsonResult getBaseSqlColumn(
            CfgDb cfgDb,
            String pageNo,
            String pageSize,
            String sqlString,
            String dbkey,
            String serviceID, Integer paramType) {
//    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (ParseSQLEnum.freemarker.getType().equals(paramType)) {
            sqlString = processSqlByFreemarker(sqlString, new HashMap<>());
        }
        List<BaseSqlconfig> list6 = new ArrayList<>();
        PageResponseVo<BaseSqlconfig> pageResponseVo = new PageResponseVo<BaseSqlconfig>();
        int b = 0;
        JsonResult jsonResult = new JsonResult();
        if (XCommonUtils.isEmpty(sqlString)) {
            return jsonResult;
        }

        Map<String, Object> rsmd;
        if (cfgDb.getDbVersion().equals("MongoDB")) {
            jsonResult = showFieldByMongoDB(cfgDb, sqlString);
            rsmd = (Map<String, Object>) jsonResult.getData();

            if (!jsonResult.getMsg().equals(""))
                return jsonResult;
        } else {
            rsmd = testOracle(cfgDb, sqlString, paramType);
        }
        if (rsmd.size() != 0) {
            List<BaseSqlconfig> list2 = new CopyOnWriteArrayList<BaseSqlconfig>();
            int showOrder = 1;
            for (Map.Entry<String, Object> entry : rsmd.entrySet()) {
                BaseSqlconfig baseSqlconfig = new BaseSqlconfig();
                baseSqlconfig.setFiledname(entry.getKey());
                baseSqlconfig.setFieldcaption(entry.getKey());
                String guid = UUID.randomUUID().toString();
                baseSqlconfig.setGuid(guid);
                baseSqlconfig.setServiceid(serviceID);
                baseSqlconfig.setShoworder(showOrder);
                baseSqlconfig.setCreatedate(new Date());
                baseSqlconfig.setCreateuser("admin");
                short showType = 0;
                String type = String.valueOf(entry.getValue());
                if ("string".equals(type)) {
                    showType = Integer.valueOf(2).shortValue();
                } else if ("date".equals(type)) {
                    showType = Integer.valueOf(1).shortValue();
                } else {
                    showType = Integer.valueOf(0).shortValue();
                }
                baseSqlconfig.setShowtype(showType);
                baseSqlconfig.setRemark(type);
                list2.add(baseSqlconfig);
                showOrder++;
            }
            int x = 0;
            List<String> list4 = baseSqlconfigMapper.selectColumnList(serviceID);
            List<BaseSqlconfig> list5 = new CopyOnWriteArrayList<BaseSqlconfig>();
            for (BaseSqlconfig bSqlconfig : list2) {
                list5.add(bSqlconfig);
            }
            for (BaseSqlconfig bs : list5) {
                for (String yString : list4) {
                    if (bs.getFiledname().equals(yString)) {
                        list5.remove(bs);
                    }
                }
            }
            if (list5.size() > 0) {
                for (BaseSqlconfig bs : list5) {
                    if (!"RN".equals(bs.getFiledname())) {
                        int f = baseSqlconfigMapper.insertSelective(bs);
                        x = x + f;
                    }
                }
            }
            redisCatchCensus.setExtAllSql(serviceID);
            list6 = baseSqlconfigMapper.selectBaseByConfig(serviceID);
//        jsonResult.setSuccess(true);
        }

        for (BaseSqlconfig baseSqlconfigs : list6) {
            if (baseSqlconfigs.getFieldcaption() == null || "".equals(baseSqlconfigs.getFieldcaption())) {
                baseSqlconfigs.setFieldcaption(baseSqlconfigs.getFiledname());
            }
        }
        pageResponseVo.setRows(list6);
        pageResponseVo.setTotal(b);
        jsonResult.setData(pageResponseVo);
        return jsonResult;
    }

    // jdbc连接数据库
    public Map<String, Object> testOracle(CfgDb cfgdb, String sqlString, Integer paramType) {
        // urls = "jdbc:oracle:thin:@192.168.0.178:1521:orcl";
        Map<String, Object> map = new HashMap<>();
        Connection con = null; // 创建一个数据库连接
        PreparedStatement pre = null; // 创建预编译语句对象，一般都是用这个而不用Statement
        ResultSet result = null; // 创建一个结果集对象
        ResultSetMetaData resultSetMetaData = null;
        try {
            Class.forName(cfgdb.getDbDrivername()); // 加载驱动程序
            System.out.println("开始尝试连接数据库！");
            String url = cfgdb.getDbUrl(); // 127.0.0.1是本机地址，XE是精简版Oracle的默认数据库名
            String user = cfgdb.getDbUser(); // 用户名,系统默认的账户名
            String password = cfgdb.getDbPwd(); // 你安装时选设置的密码
            con = DriverManager.getConnection(url, user, password); // 获取连接
            System.out.println("连接成功！");
            Map<String, Object> map2 = new HashMap<>();
            String sql = "";
            if (ObjectUtil.isEmpty(paramType) || ParseSQLEnum.freemarker.getType().equals(paramType)) {
                sqlString = processSqlByFreemarker(sqlString, map2);
                if (sqlString.contains(";")) {
                    sqlString = sqlString.replaceAll(";", " ");
                }
                // 预编译语句，“？”代表参数
                sql = "select * from (" + sqlString + ") a where 1=0";
                pre = con.prepareStatement(sql); // 实例化预编译语句

            } else {
                SqlData sqlData = ognlParseSQLStrategy.parseSQLGetField(sqlString, new HashMap<>());
                sql = sqlData.getSql();
                //避免全表扫描
                sql = "select * from (" + sql + ") a where 1=0";
                pre = con.prepareStatement(sql); // 实例化预编译语句

                // 统计 SQL 语句中占位符的数量
                int placeholderCount = sql.replaceAll("[^?]", "").length();

                if (!sqlData.getParamList().isEmpty()) {
                    int index = 0;
                    for (int i = 0; i < placeholderCount; i++) {
                        pre.setNull(++index, java.sql.Types.NULL);
                    }
                }
            }


            result = pre.executeQuery(); // 执行查询，注意括号中不需要再加参数
            resultSetMetaData = result.getMetaData();
            //String aString = String.valueOf(resultSetMetaData.getColumnCount());
            for (int i = 1; i <= Integer.parseInt(String.valueOf(resultSetMetaData.getColumnCount())); i++) {
                String columnType = "";
        /*System.out.println(resultSetMetaData.getColumnName(i) + "++++++++++++++++"
        + resultSetMetaData.getColumnTypeName(i));*/
                String as = resultSetMetaData.getColumnTypeName(i);
                if ("TIME".equals(as.toUpperCase())) {
                    columnType = "date";
                } else if ("DATETIME".equals(as.toUpperCase())) {
                    columnType = "date";
                } else if ("timestamp".equals(as.toLowerCase())) {
                    columnType = "date";
                } else if ("date".equals(as.toLowerCase())) {
                    columnType = "date";
                } else if ("char".equals(as.toLowerCase())) {
                    columnType = "string";
                } else if ("text".equals(as.toLowerCase())) {
                    columnType = "string";
                } else if ("varchar2".equals(as.toLowerCase())) {
                    columnType = "string";
                } else if ("nvarchar2".equals(as.toLowerCase())) {
                    columnType = "string";
                } else if ("nvarchar".equals(as.toLowerCase())) {
                    columnType = "string";
                } else if ("varchar".equals(as.toLowerCase())) {
                    columnType = "string";
                } // Add By Cocoliu 2017/11/9 增加clob、nclob、blob类型
                else if ("clob".equals(as.toLowerCase())) {
                    columnType = "clob";
                } else if ("nclob".equals(as.toLowerCase())) {
                    columnType = "clob";
                } else if ("blob".equals(as.toLowerCase())) {
                    columnType = "blob";
                } else {
                    columnType = "int";
                }
                // System.out.println(resultSetMetaData.getColumnTypeName(i)+"==========================="+resultSetMetaData.getColumnName(i));
                map.put(resultSetMetaData.getColumnName(i), columnType);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException(ResultCodeEnum.SQL_EXCEPTION, String.valueOf(e));
        } finally {
            try {
                // 逐一将上面的几个对象关闭，因为不关闭的话会影响性能、并且占用资源
                // 注意关闭的顺序，最后使用的最先关闭
                if (result != null) result.close();
                if (pre != null) pre.close();
                if (con != null) con.close();
                System.out.println("数据库连接已关闭！");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    /**
     * TODO: 获取 MongoDB 集合中的字段
     *
     * @param cfgdb
     * @param sqlString
     * @return
     */
    private JsonResult showFieldByMongoDB(CfgDb cfgdb, String sqlString) {
        Map<String, Object> map2 = new HashMap<>();
        JsonResult jsonResult = new JsonResult();
        sqlString = processSqlByFreemarker(sqlString, map2);
        if (sqlString.contains(";")) {
            sqlString = sqlString.replaceAll(";", " ");
        }
        MongoDBUtil instance = MongoDBUtil.getInstance();
        QueryInfo queryInfo = instance.sql2MongoQuery(sqlString);
        if (queryInfo != null) {
            BasicDBObject fields = queryInfo.getFields();
            if (fields == null || fields.size() == 0) {
                // 获取集合中的字段名称
                queryInfo.setDb(instance.createConnection(cfgdb.getDbUrl()));
                fields = instance.getFields(queryInfo);
                instance.close();

                if (fields == null || fields.size() == 0) {
                    jsonResult.setSuccess(false);
                    jsonResult.setMsg("MongoDB 必须指定查询的列名~");
                }
            }
            fields.forEach((s, o) -> map2.put(s, "string"));
//      jsonResult.setSuccess(true);
        }
        jsonResult.setData(map2);
        return jsonResult;
    }

    @Override
    public List<Map<String, Object>> executequerySql(CfgDb cfgDb, String sqlString) {
        List<Map<String, Object>> list = executeSqlMapper.executequerySql(sqlString);
        return list;
    }

    @Override
    public List<Map<String, Object>> executequerySqls(String uuid, CfgDb cfgDb, String sqlString)
            throws BaseException {
        List<CfgTable> lists = null;
        String sqlException = "";
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> columnMap = new HashMap<>();
        List<String> list2 = new ArrayList<>();
        list2.add("cfgdb");
        Gson gson = new Gson();
        int i = 1;
        try {
            // lists = extCfgTableMapper.selectAllShortTable();
            //			amqpTemplate.convertAndSend("directExchange", RabbitMQRoutingKey.serverQueueDestination,
            // JSON.toJSONString(server));
            //			ActiveMQUtil.saveActivemqString(jmsTemplate, destination, uuid, "1111111111");
            //			ActiveMQUtil.saveActivemqString(jmsTemplate, destination, uuid, "2222222222");
            System.out.println(uuid);
            Map<String, Object> map = new HashMap<>();
            map.put("guid", "GUI");
            map.put("order", "GUI");
            CfgTable cfgTable = new CfgTable();
            cfgTable.setGuid("GUI");
            cfgTable.setDtOrder("GUI");
            //			if (i==1) {
            //				SqlInterceptor
            //				sql
            //			}
            String sql =
                    sqlSessionFactory
                            .getConfiguration()
                            .getMappedStatement(
                                    "com.elitel.frame.main.dao.ext.ExtCfgTableMapper.selectAllShortTable")
                            .getBoundSql(null)
                            .getSql();
            String sql1 =
                    sqlSessionFactory
                            .getConfiguration()
                            .getMappedStatement(
                                    "com.elitel.frame.main.dao.CfgTableMapper.updateByPrimaryKeySelective")
                            .getBoundSql(cfgDb)
                            .getSql();
            MyBatisSql myBatisSql =
                    MyBatisSqlUtils.getMyBatisSql(
                            "com.elitel.frame.main.dao.ext.ExtCfgTableMapper.selectAllShortTable",
                            map,
                            sqlSessionFactory);
            // updateByPrimaryKeySelective
            MyBatisSql myBatisSql2 =
                    MyBatisSqlUtils.getMyBatisSql(
                            "com.elitel.frame.main.dao.CfgTableMapper.updateByPrimaryKeySelective",
                            map,
                            sqlSessionFactory);
            System.out.println(myBatisSql.toString());
            sqlException = sql;
            System.out.println(sql1);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            CfgTableMapper countryMapper = sqlSession.getMapper(CfgTableMapper.class);
            String xx =
                    SqlHelper.getMapperSql(
                            sqlSession, "com.elitel.frame.main.dao.CfgTableMapper.getBiaoChinese", list2);
            // MyBatisSqlUtils.getMyBatisSql("selectAllShortTable", map, sqlSessionFactory)
            columnMap.put(sql, gson.toJson(lists));
            if (columnMap.size() > 0) {
                //				ActiveMQUtil.saveActivemqString(jmsTemplate, destination, uuid, columnMap.toString());
            }
        } catch (Exception e) {
            throw new BaseException(e, sqlException, getSysException());
        }
        return list;
    }

    public Map<String, SysException> getSysException() {
        List<Map<String, Object>> lists = null;
        Map<String, SysException> map = new HashMap<>();
        List<SysException> list = extSysExceptionMapper.selectAllList();
        for (SysException sysException : list) {
            map.put(sysException.getExceptionName(), sysException);
        }
        return map;
    }
}
